//
//  BENetworkTools.swift
//  BEGlobalOiler
//
//  Created by KKING on 16/9/8.
//  Copyright © 2016年 Bullseye Energy pte ltd. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

/// 网络请求回调
typealias NetworkFinished = (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()

class BENetworkTools: NSObject {
    
    /// 网络工具类单例
    static let shareNetworkTool = BENetworkTools()
}

// MARK: - 基础请求方法
extension BENetworkTools {
    
    /**
     GET请求
     
     - parameter APIString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func get(APIString: String, parameters: [String : AnyObject]?, finished: @escaping NetworkFinished) {
        
        //        print("\(BASE_URL)\(APIString)")
        Alamofire.request("\(BASE_URL)\(APIString)", method: .get,parameters: parameters).responseJSON { (response) in
            
            guard response.result.isSuccess else {
                JFProgressHUD.showErrorWithStatus(status: "加载失败...")
                finished(false, nil, response.result.error as NSError?)
                return
            }
            if let value = response.result.value {
                let json = JSON(value)
                finished(true, json, nil)
            }
        }
    }
    
    /**
     带token的GET请求
     
     - parameter APIString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func getWithToken(APIString: String, parameters: [String : AnyObject]?, finished: @escaping NetworkFinished) {
        
        guard let token = BEAccountModel.shareAccount()?.authToken else {
            return
        }
        
        //        print("\(BASE_URL)\(APIString)")
        Alamofire.request("\(BASE_URL)\(APIString)", method: .get , parameters: parameters, headers: ["Authorization" : "\(token)"]).responseJSON { (response) in
            
            guard response.result.isSuccess else {
                JFProgressHUD.showErrorWithStatus(status: "加载失败...")
                finished(false, nil, response.result.error as NSError?)
                return
            }
            if let value = response.result.value {
                let json = JSON(value)
                finished(true, json, nil)
            }
        }
    }
    
    
    /**
     POST请求
     
     - parameter APIString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func post(APIString: String, parameters: [String : AnyObject]?, finished: @escaping NetworkFinished) {

        Alamofire.request("\(BASE_URL)\(APIString)", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { (response) in
            guard response.result.isSuccess else {
                JFProgressHUD.showErrorWithStatus(status: "加载失败...")
                finished(false, nil, response.result.error as NSError?)
                return
            }
            if let value = response.result.value {
                let json = JSON(value)
                finished(true, json, nil)
            }
        }
    }
    
    /**
     带token的POST请求
     
     - parameter APIString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func postWithToken(APIString: String, parameters: [String : AnyObject]?, finished: @escaping NetworkFinished) {
        
        guard let token = BEAccountModel.shareAccount()?.authToken else {
            return
        }
        
        Alamofire.request("\(BASE_URL)\(APIString)", method: .post,parameters: parameters, encoding: JSONEncoding.default, headers: ["Authorization" : "\(token)"]).responseJSON { (response) in
            guard response.result.isSuccess else {
                JFProgressHUD.showErrorWithStatus(status: "加载失败...")
                finished(false, nil, response.result.error as NSError?)
                return
            }
            if let value = response.result.value {
                let json = JSON(value)
                finished(true, json, nil)
            }
        }
    }
}


// MARK: - 辅助方法
extension BENetworkTools {
    
    /**
     对象转json
     */
    private func objectToJson(object: AnyObject) -> NSString? {
        do {
            let data = try JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions.prettyPrinted)
            return NSString(data: data, encoding: String.Encoding.utf8.rawValue)
        } catch {
            return nil
        }
    }
    
    /**
     获取当前网络状态
     
     - returns: 0未知 1WiFi 22G 33G 44G
     */
    func getCurrentNetworkState() -> Int {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.networkState
    }
}



//登录 工单列表 工单详情 创建订单 确认订单 确认订单完成
extension BENetworkTools{
    //获得平台信息,银行卡保存到沙盒中.
    func getPlatformInfo(finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        get(APIString: GET_PLATFORM_INFO, parameters: nil, finished: finished)
    }
    
    //登录
    func normalAccountLogin(username: String, password: String, finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        var deviceToken = UserDefaults.standard.object(forKey: "deviceToken")
        
        if deviceToken == nil {
            deviceToken = NSNull()
        }
        let parameters: [String : AnyObject] = [
            "userName" : username as AnyObject,
            "password" : password as AnyObject,
            "iosDeviceToken": NSNull()
        ]
        //        print(deviceToken!)
        post(APIString: LOGIN, parameters: parameters, finished: finished)
    }
    
    //查询订单列表
    func loadOrderListData(finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        getWithToken(APIString: GET_ORDER_LIST, parameters: nil, finished: finished)
    }
    /*
     @IBAction func confirmBtnDidClick(sender: AnyObject) {
     
     }
     
     @IBAction func departBtnDidClick(sender: AnyObject) {
     
     }
     
     @IBAction func repairingBtnDidClick(sender: AnyObject) {
     
     }
     
     @IBAction func repairedBtnDidClick
     */
    
    //确认订单
    func confirmOrder(orderId: Int64,finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        let parameters = [
            "longitude": "string",
            "latitude": "string",
            "address": "string"
        ]
        let POST_ORDER_CONFIRM_NEW = POST_ORDER_CONFIRM + "\(orderId)" + "/confirm"
        postWithToken(APIString: POST_ORDER_CONFIRM_NEW, parameters: parameters as [String : AnyObject]?, finished: finished)
    }
    
    //出发
    func talentDepart(orderId: Int64,finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        let parameters = [
            "longitude": "string",
            "latitude": "string",
            "address": "string"
        ]
        let POST_DEPART_NEW = POST_DEPART + "\(orderId)" + "/depart"
        postWithToken(APIString: POST_DEPART_NEW, parameters: parameters as [String : AnyObject]?, finished: finished)
    }
    
    //开始维修 POST /v1/order/talent/{orderId}/repairing
    func talentRepairing(orderId: Int64,finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        let parameters = [
            "longitude": "string",
            "latitude": "string",
            "address": "string"
        ]
        let POST_REPARING_NEW = POST_REPAIRING + "\(orderId)" + "/repairing"
        postWithToken(APIString: POST_REPARING_NEW, parameters: parameters as [String : AnyObject]?, finished: finished)
    }
    
    //维修完成 POST /v1/order/talent/{orderId}/repaired
    func talentRepaired(orderId: Int64,finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        let parameters = [
            "longitude": "string",
            "latitude": "string",
            "address": "string"
        ]
        let POST_REPAIRED_NEW = POST_REPAIRED + "\(orderId)" + "/repaired"
        postWithToken(APIString: POST_REPAIRED_NEW, parameters: parameters as [String : AnyObject]?, finished: finished)
    }
    
    //准备报告 POST /v1/order/talent/{orderId}/preparingPackage
    func preparingPackage(orderId: Int64,finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        let parameters = [
            "longitude": "string",
            "latitude": "string",
            "address": "string"
        ]
        let POST_PREPAIRINGPACKAGE_NEW = POST_PREPAIRINGPACKAGE + "\(orderId)" + "/preparingPackage"
        postWithToken(APIString: POST_PREPAIRINGPACKAGE_NEW, parameters: parameters as [String : AnyObject]?, finished: finished)
    }
    
    //上传报告 POST /v1/order/talent/{orderId}/packageUploaded
    func packageUploaded(orderId: Int64,finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        let paramters =   ["resourcesIdList": NSArray(object: NSNumber(value:3814638712793464832)),
                           "locationVO": [
                            "longitude": "string",
                            "latitude": "string",
                            "address": "string"
                            ]
                        ] as [String : Any]
        let POST_DEPART_NEW = POST_DEPART + "\(orderId)" + "/packageUploaded"
        postWithToken(APIString: POST_DEPART_NEW, parameters: paramters as [String : AnyObject]?, finished: finished)
    }
    
    //上传报销POST /v1/order/talent/{orderId}/expenseUploaded
    func expenseUploaded(orderId: Int64,finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        let parameters = [
            "longitude": "string",
            "latitude": "string",
            "address": "string"
        ]
        let POST_DEPART_NEW = POST_DEPART + "\(orderId)" + "/expenseUploaded"
        postWithToken(APIString: POST_DEPART_NEW, parameters: parameters as [String : AnyObject]?, finished: finished)
    }
    
}


